package libra.controller;

import java.time.LocalDateTime;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import libra.model.JsonResult;
import libra.model.seate.OrderDetails;
import libraServer.dao.Dao;

@RestController
public class OrderController {
	@Autowired
	Dao dao;
	@Autowired
	RestTemplate restTemplate;
	
	@Value( "#{'${server.servlet.context-path}'.concat('[port(${server.port})]')}" )
	String identity;
	
//	String urlPrefix = "http://127.0.0.1:20310/signle_provider_payment_20310";
	/*
	 *  通过@LoadBalanced开启负载均衡可以通过应用服务名，调用服务接口
	 *  格式http://应用服务名（区分大小写）/[应用项目名称]/接口地址
	 */
	String urlPrefix = "http://seata-goods" + "/goods_40100";
	
//	@Autowired
//    private LoadBalancerClient loadBalancerClient;
//	@PostConstruct
//	public void init() {
//		ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-single-provider");
//		urlPrefix = String.format("http://%s:%s/%s",serviceInstance.getHost(),serviceInstance.getPort(),"nacos_single_consumer_30300");
//	}
	
	@GlobalTransactional
//	@Transactional(rollbackFor = Exception.class)
	@RequestMapping("buy")
	public JsonResult<?> buy( Integer goods_id, Integer count, Boolean isSelfEx, Boolean isEx, HttpServletRequest req, HttpServletResponse resp ) throws Exception{
		// 获取 XID
		String xid = RootContext.getXID();
		System.err.println( "获取XID【OrderController.buy()】:"+xid );
		// 创建订单记录
		OrderDetails orderDetails = sql_RecordOrderDetails(goods_id, count);
		// 调用Goods模块减商品库存，并记录库存流水
		// 封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("goods_id", goods_id);
        paramMap.add("count", count);
        paramMap.add("order_id", orderDetails.getId());
        paramMap.add("isEx", isEx);
		JsonResult<Map<String, Object>> postForObject = restTemplate.postForObject(urlPrefix+"/stock", paramMap, JsonResult.class);
        
        @SuppressWarnings("unused")
		int i = 1/(isSelfEx?0:1);
        
        Map<String, Object> map = postForObject.getObj();
        map.put("orderDetails", orderDetails.toString());
		return new JsonResult<Object>( 0, identity, map);
	}
	
	/**
	 * 记录订单
	 * @param goods_id 商品id
	 * @param count 下单数量
	 * @throws Exception 
	 */
	@GlobalTransactional
	public OrderDetails sql_RecordOrderDetails( Integer goods_id, Integer count ) throws Exception {
		// 本地下单
		OrderDetails orderDetails = new OrderDetails(goods_id, count, LocalDateTime.now().toString());
		dao.save(orderDetails);
		return orderDetails;
	}
}


